<template>
  
  <van-form @submit="onSubmit">
    <van-cell-group inset>
<!--      活动标题-->
      <van-field
          v-model="act.title.value"
          required
          name="title"
          label="活动标题"
          placeholder="请输入活动标题"
          maxlength="30"
          show-word-limit
          clearable
          :rules="act.title.rules"
      />
<!--      活动分区-->
      <van-field
          v-model="act.catId.value.text"
          required
          is-link
          readonly
          name="catId"
          label="分区"
          placeholder="点击选择活动分区"
          @click="act.catId.showPicker = true"
          :rules="act.catId.rules"
      >
      </van-field>
      <van-popup v-model:show="act.catId.showPicker" round position="bottom">
        <van-picker
            title="选择活动分区"
            :columns="act.catId.catList"
            @cancel="act.catId.showPicker = false"
            @confirm="act.catId.onConfirm"
        />
      </van-popup>
<!--      活动详情-->
      <van-field
          type="textarea"
          v-model="act.info.value"
          required
          name="info"
          rows="3"
          autosize
          label="详情"
          maxlength="1000"
          placeholder="请填写活动详情"
          show-word-limit
          clearable
          :rules="act.info.rules"
      />
<!--      活动地点-->
      <van-field
          v-model="act.place.value"
          required
          name="place"
          label="地点"
          maxlength="30"
          placeholder="请填写活动地点"
          show-word-limit
          :rules="act.place.rules"
      />
<!--      活动开始时间与结束时间-->
      <van-field
          v-model="act.startTime.value"
          is-link
          readonly
          name="startTime"
          label="开始时间"
          required
          placeholder="点击选择活动开始时间"
          @click="act.startTime.showPicker = true"
          :rules="act.startTime.rules"
      />
      <van-popup v-model:show="act.startTime.showPicker" position="bottom">
        <van-picker-group
            title="选择活动开始时间"
            :tabs="['日期', '时间']"
            @confirm="act.startTime.onConfirm"
            @cancel="act.startTime.showPicker = false"
        >
          <van-date-picker
              v-model="act.startTime.date"
              :min-date="act.startTime.minDate"
              :max-date="act.startTime.maxDate"
          />
          <van-time-picker
              v-model="act.startTime.time"
          />
        </van-picker-group>
      </van-popup>
<!--      活动结束时间-->
      <van-field
          v-model="act.endTime.value"
          is-link
          readonly
          name="endTime"
          label="结束时间"
          required
          placeholder="点击选择活动结束时间"
          @click="act.endTime.showPicker = true"
          :rules="act.endTime.rules"
      />
      <van-popup v-model:show="act.endTime.showPicker" position="bottom">
        <van-picker-group
            title="选择活动结束时间"
            :tabs="['日期', '时间']"
            @confirm="act.endTime.onConfirm"
            @cancel="act.endTime.showPicker = false"
        >
          <van-date-picker
              v-model="act.endTime.date"
              :min-date="dateUtil.getDateByArray(act.startTime.date)"
              :max-date="act.endTime.maxDate"
          />
          <van-time-picker
              v-model="act.endTime.time"
          />
        </van-picker-group>
      </van-popup>

<!--      活动人数-->
      <van-field
          name="size"
          label="活动人数"
          required
          :error="act.size.error"
          :error-message="act.size.errorMsg"
      >
        <template #input>
          <div style="display: flex; flex-direction: column">
            <van-stepper
                :min="-1"
                v-model="act.size.value"
                @change="sizeValidator"
            />
            <div style="font-size: 12px">
              -1表示无人数限制；不可为0
            </div>
          </div>
        </template>
      </van-field>
      
<!--      图片上传-->
      <van-field name="uploader" label="图片">
        <template #input>
          <ImgUploader :max-count="3" ref="imgUploader"/>
        </template>
      </van-field>
    </van-cell-group>
    <div class="separator-div"/>
    
    
    <div style="text-align: center" class="edit-question-head">
      <span>活动问卷编辑</span>
    </div>
    <div style="padding: 0 5px;">
      <div
          style="margin-bottom: 5px"
          class="edit-question-div"
          v-for="(item, index) in qn">
        <QuestionItem
            :q="item"
            edit
            @up="qUp(index)"
            @down="qDown(index)"
            @del="qDel(index)"
        />
      </div>
      
    </div>
    <div style="text-align: center">
      <van-button icon="plus" type="primary" plain @click="showQPicker = true">添加题目</van-button>
      <van-popup v-model:show="showQPicker" round position="bottom">
        <van-picker
            title="添加问卷题目"
            :columns="[{text: '填空题', value: 0},{text: '单选题', value: 1},{text: '多选题', value: 2}]"
            @cancel="showQPicker = false"
            @confirm="addQ"
        />
      </van-popup>
    </div>
    
    <div style="margin: 16px;">
      <van-button
          round
          block
          type="primary"
          native-type="submit"
          :loading="loading"
      >
        提交
      </van-button>
    </div>
  </van-form>
</template>

<script>
import {defineComponent} from 'vue'
import catApi from "@/utils/api/catApi";
import dateUtil from "@/utils/dateUtil";
import actApi from "@/utils/api/actApi";
import DBConst from "@/consts/DBConst";
import QuestionItem from "@/views/act/components/QuestionItem.vue";
import arrUtil from "@/utils/arrUtil";
import {showConfirmDialog, showFailToast, showLoadingToast, showSuccessToast, showToast} from "vant";
import ImgUploader from "@/components/ImgUploader.vue";
export default defineComponent({
  components: {ImgUploader, QuestionItem},
  setup(){
    return {
      dateUtil,
      arrUtil
    }
  },
  name: "EditAct",
  created() {
    this.getCatList()
    if(this.$route.query.actId){
      this.getActInfo()
    }
  },
  data(){
    return {
      loading: false,
      act: {
        actId: null,
        title: {
          value: '',
          rules: [
            {
              formatter: (s) => {
                s = s.trim()
                this.act.title.value = s
                return s
              },
              required: true,
              message: '请填写活动标题',
              trigger: 'onBlur'
            }
          ]
        },
        catId:{
          catList: [],
          showPicker: false,
          value: {text: ''},
          rules: [
            {
              required: true,
              message: '请选择活动分区',
              trigger: 'onBlur'
            }
          ],
          onConfirm: ({ selectedOptions })=>{
            this.act.catId.showPicker = false;
            this.act.catId.value = selectedOptions[0]
          }
        },
        info: {
          value: '',
          rules: [
            {
              formatter: (s) => {
                s = s.trim()
                this.act.info.value = s
                return s
              },
              required: true,
              message: '请填写活动详情',
              trigger: 'onBlur'
            }
          ]
        },
        place: {
          value: '',
          rules: [
            {
              formatter: (s) => {
                s = s.trim()
                this.act.place.value = s
                return s
              },
              required: true,
              message: '请填写活动地点',
              trigger: 'onBlur'
            }
          ]
        },
        startTime: {
          minDate: new Date(),
          maxDate: this.getMaxDate(),
          date: dateUtil.getDateArray(new Date()),
          time: ['00','00'],
          showPicker: false,
          value: '',
          rules: [
            {
              required: true,
              message: '请填写活动开始时间',
              trigger: 'onBlur'
            }
          ],
          onConfirm: () => {
            this.act.startTime.value = `${this.act.startTime.date.join('-')} ${this.act.startTime.time.join(':')}`
            this.act.startTime.showPicker = false;
          }
        },
        endTime: {
          minDate: new Date(),
          maxDate: this.getMaxDate(),
          date: dateUtil.getDateArray(new Date()),
          time: ['00','00'],
          showPicker: false,
          value: '',
          rules: [
            {
              required: true,
              message: '请填写活动开始时间',
              trigger: 'onBlur'
            },
              this.dateCmpValidator()
          ],
          onConfirm: () => {
            this.act.endTime.value = `${this.act.endTime.date.join('-')} ${this.act.endTime.time.join(':')}`
            this.act.endTime.showPicker = false;
          }
        },
        size: {
          error: false,
          errorMsg: '',
          value: -1,
        },
      },
      qn: [],
      showQPicker: false
    }
  },
  methods: {
    async onSubmit(){
      if(this.sizeValidator()){
        let act = {
          actId: this.act.actId,
          catIds: [this.act.catId.value.value],
          title: this.act.title.value,
          info: this.act.info.value,
          place: this.act.place.value,
          startTime: this.act.startTime.value,
          endTime: this.act.endTime.value,
          size: this.act.size.value,
          qn: this.qn.map(item=>{
            if(item.type === DBConst.QType.BLANK){
              return item
            }else{
              return {
                title: item.title,
                type: item.type,
                options: item.options.map(o=>{
                  return o.info
                })
              }
            }
          }),
          imgIdList: this.$refs.imgUploader.getImgIdList()
        }
        
        try {
          this.loading = true
          showLoadingToast({
            message: '提交中...',
            forbidClick: true,
            duration: 0
          });
          if(this.$route.query.actId){
            //修改
            await actApi.updateAct(act, this.$refs.imgUploader.getFileList())
          }else {
            act.actId = await actApi.createAct(act, this.$refs.imgUploader.getFileList())
          }
          showSuccessToast('提交成功')
          this.$router.replace({
            path: '/act/info',
            query: {actId: act.actId}
          })
        }catch (data){
        
        }finally {
          this.loading = false
        }
        
        
      }
    },
    async getCatList() {
      let catList = await catApi.listCat()
      this.act.catId.catList = catList.map(item => {
        return {text: item.cat, value: item.catId}
      })
    },
    async getActInfo(){
      let data = await actApi.getActInfo(this.$route.query.actId)
      let act = data.act
      
      this.act.actId = act.actId
      this.act.title.value = act.title
      this.act.catId.value = {text: act.cats[0].cat, value: act.cats[0].catId}
      this.act.info.value = act.info
      this.act.place.value = act.place
      this.act.startTime.value = act.startTime
      this.act.endTime.value = act.endTime
      this.act.size.value = act.size
      
      let qn = data.qn
      this.qn = qn
      
      // this.act.imgFileList = act.imgs.map(item=>{
      //   item.isImage = true
      //   return item
      // })
      this.$refs.imgUploader.init(act.imgs)
    },
    getMaxDate(){
      let date = new Date()
      date.setMonth(date.getMonth() + 3)
      return date
    },
    dateCmpValidator(){
      return {
        validator: ()=>{
          if(this.act.startTime.value !=='' && this.act.endTime.value !== ''){
            let cmp = dateUtil.cmpDateStr(this.act.startTime.value, this.act.endTime.value)
            return cmp < 0
          }
          return true
        },
        message: '开始时间必须比结束时间早',
        trigger: 'onChange',
      }
    },
    sizeValidator(){
      if(this.act.size.value === 0){
        this.act.size.error = true
        this.act.size.errorMsg = '人数不可为0'
      }else {
        this.act.size.error = false
        this.act.size.errorMsg = ''
      }
      return !this.act.size.error
    },
    addQ({ selectedOptions }){
      switch (selectedOptions[0].value){
        case DBConst.QType.BLANK:{
          this.qn.push({
            title: `填空题——${this.qn.length + 1}`,
            type: DBConst.QType.BLANK,
            options: []
          })
          break
        }
        case DBConst.QType.SINGLE: {
          this.qn.push({
            title: `单选题——${this.qn.length + 1}`,
            type: DBConst.QType.SINGLE,
            options: [
              {info: '选项1'},
              {info: '选项2'},
              {info: '选项3'},
              {info: '选项4'},
            ]
          })
          break
        }
        case DBConst.QType.MULTI: {
          this.qn.push({
            title: `多选题——${this.qn.length + 1}`,
            type: DBConst.QType.MULTI,
            options: [
              {info: '选项1'},
              {info: '选项2'},
              {info: '选项3'},
              {info: '选项4'},
            ]
          })
          break
        }
      }
      this.showQPicker = false
    },
    qUp(index){
      arrUtil.moveElementForward(this.qn, index)
      showToast('题目已前移')
    },
    qDown(index){
      arrUtil.moveElementBackward(this.qn, index)
      showToast('题目已后移')
    },
    qDel(index){
      showConfirmDialog({
        title: '标题',
        message:
            `是否确认删除题目：${this.qn[index].title} ?`,
      })
        .then(() => {
          // on confirm
          this.qn.splice(index, 1)
        })
        .catch(() => {
          // on cancel
        });
    }
  },

})
</script>



<style scoped lang="less">
@import "@/assets/style/less/all.less";
.edit-question-div{
  border-radius: 5px;
  font-size: 14px;
  box-shadow: 0 3px 10px -5px @input_border_shadow_color;
  border: 1px solid @input_border_color;
}
.edit-question-head{
  padding: 3px;
  margin: 3px;
  font-size: 20px;
}
</style>